﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Windows.Forms;
using Segmentator.Dividers;

namespace Segmentator.IntegrityThroughInterval
{
    /* Сериализация и десериализация сегментатора цепи*/
    class DividerManager
    {
        private OpenFileDialog openFileDialog1;
        private Divider _dvd = null;
        private List<string> forCombobox = null;
        protected Stack<Divider> dvdStack = null;

        public DividerManager()
        {
            openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Multiselect = true;
            forCombobox = new List<string>();
            dvdStack = new Stack<Divider>();
        }

        /* Создать ранее сохранную копию объекта*/
        public Divider Load()
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fileName;
                fileName = openFileDialog1.FileName;
                FileStream fs = SaveToStream(fileName);
                fs.Close();
            }

            return _dvd;
        }

        private FileStream SaveToStream(string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            BinaryFormatter bf = new BinaryFormatter();
            _dvd = (Divider)bf.Deserialize(fs);
            return fs;
        }

        /* Создать ранее сохранные копии объекта*/
        public void MultyLoad()
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string[] fileNames;
                fileNames = openFileDialog1.FileNames;
                foreach (string s in fileNames)
                {
                    FileStream fs = SaveToStream(s);
                    dvdStack.Push(_dvd);
                    fs.Close();

                    forCombobox.Add(new FileInfo(s).Name);
                }
            }

        }
        /* Сохранить копию объекта*/
        public void Save(Divider divider, TextBox fileName)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream fs = new FileStream(Application.StartupPath + "\\Serializations\\" + fileName.Text, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            formatter.Serialize(fs, divider);
            fs.Close();
        }

        public List<string> GetDividerNames()
        {
            return forCombobox;
        }

      

    }
}
